<?php
namespace app\logic;

use think\facade\Db;

class DeptHelper
{
    public static function get_dept_names($dept_ids) {
        if (empty($dept_ids)) return '';

        $list = DataHelper::select("tb_dept", "id in ($dept_ids)", [
            'order_by' => 'idx desc',
            'with_power' => false
        ]);
        $dept_names = '';
        foreach ($list as $item) {
            $dept_names .= $item["title"].',';
        }
        $dept_names = trim($dept_names, ',');

        return [$dept_ids, $dept_names];
    }

    public static function expand_dept_ids($dept_ids) {
        $dept_ids_new = [];
        $dept_titles_new = [];

        $dept_ids = explode(',', $dept_ids);
        foreach ($dept_ids as $dept_id) {
            if ($dept_id > 0) {
                $dept = DataHelper::find_by_id('tb_dept', $dept_id);

                $dept_ids_new[] = $dept_id;
                $dept_titles_new[] = $dept['title'];

                if ($dept['pid'] > 0) {
                    $dept_ids_new[] = $dept['pid'];
                    $dept_titles_new[] = $dept['pname'];
                }
            }
        }

        $dept_ids_new = array_unique($dept_ids_new);
        $dept_titles_new = array_unique($dept_titles_new);

        return [$dept_ids_new, $dept_titles_new];
    }

    public static function load_role_dept($pid, $role_id) {
        $role = DataHelper::find_by_id('tb_role', $role_id);


        $list = DataHelper::select('tb_dept', [
            [ 'pid', '=', $pid ],
            [ 'id', 'in', explode(',', $role['dept_ids']) ],
            [ 'status', '=', 0 ],
        ], [
            'order_by' => 'idx desc',
            'with_power' => false
        ]);

        foreach ($list as &$item) {
            $children = self::load_role_dept($item['id'], $role_id);
            $item['children'] = $children;
        }

        return $list;
    }

    public static function load_dept($pid = 0, $checked_ids = []) {

        $list = DataHelper::select('tb_dept', [
            [ 'pid', '=', $pid ],
            [ 'status', '=', 0 ],
        ], "idx desc", [ 'with_power' => false ]);

        foreach ($list as &$item) {
            if (in_array($item['id'], $checked_ids)) {
                $item['checked'] = true;
            }
        }

        foreach ($list as &$item) {
            $children = self::load_dept($item['id'], $checked_ids);
            $item['children'] = $children;
        }

        return $list;
    }
}